home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2772 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  52 lines

  1. Path: amaryllisp1.appsig.com!user
  2. From: larry_kearney@appsig.com (Lawrence Kearney)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: help with pi algorithm
  5. Date: Tue, 23 Jan 1996 13:15:38 -0700
  6. Organization: Applied Signal Technology
  7. Message-ID: <larry_kearney-2301961315380001@amaryllisp1.appsig.com>
  8. References: <0fc_9601240111@csource.blaze.net.au>
  9. NNTP-Posting-Host: amaryllisp1.appsig.com
  10.  
  11. > I am a newbie C programmer trying to write an algorithm to work out the
  12. > value of pi fairly accurately. I have written the following code, but I'm
  13. > not sure whether it's considered 'nasty' programming, or whether it could
  14. > be written to run more quickly.
  15. > #include <stdio.h>
  16. > main()
  17. > {
  18. >    long double pi = 0;
  19. >    long int = count;
  20. >    for (count = 1; count <= 300000; count += 4) {
  21. >       pi += 4.0 / count;            pi -= 4.0 / (count + 2);
  22. >    }
  23. >    printf("Value of pi is approx %.19Lf)", pi);
  24. >    return 0;
  25. > }
  26. > Any comments please???
  27.  
  28. The algorithm you've chosen is a poor one in that it will converge to pi
  29. very, very, slowly (in, in fact, it converges at all. I don't know as I
  30. haven't tested it).  Rather than trying to speed this one up, I would
  31. suggest that you invest some time looking for one that converges at a
  32. faster rate.
  33.  
  34. If you insist on using this algorithm, I would suggest that you keep all
  35. the values in your computation as long doubles rather than making the
  36. compiler continually convert long ints to long doubles, a very expensive
  37. process. You don't need to tie count to the loop variable, just create a
  38. separate variable for the loop index.
  39.  
  40. This concept of finding better algorithms instead of spending time
  41. optimizing poor ones is true in a large number of cases. Although yours is
  42. a simple case and is intended to help you learn how to program in C, as
  43. you become more experienced and find yourself attempting to write fast,
  44. efficient programs, you'll find that it applies more and more.
  45.  
  46. -- 
  47. Larry Kearney                   |   "You want fries with that?"
  48. Applied Signal Technology       |
  49. larry_kearney@appsig.com        |
  50.